const express = require('express');

const path =require('path');

//导入express-session模块
// const session = require('express-session')

// 处理文件上传
const formidableMiddleware = require('express-formidable');
//token 用于生成jwt字符串
const jwt = require('jsonwebtoken');
//解决vue路由history模式404的问题
const  history = require('connect-history-api-fallback')
// express-jwt 用于将jwt字符串还原成json对象
const expressJWT = require('express-jwt')



const admin = require('./router/admin')
const uploads = require('./router/upload')
const classify = require('./router/class')
const article = require('./router/article')
const tag = require('./router/tag')
const content = require('./router/content')
const message = require('./router/message')

require('./model/connect.js');

const app = express();
app.use((req,res,next)=>{
    res.header('Access-Control-Allow-Origin', '*');

    res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept , Authorization ');

    res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");

    next();
})
app.use(history())
// app.use(session({
// 	secret:'secret key',
// 	  saveUninitialized: false,
// 	  cookie:{
// 		  maxAge:24*60*60*1000
// 	  }, 
//       resave: false, //添加 resave 选项
//       saveUninitialized: true, //添加 saveUninitialized 选项
// 	}));

// 处理post参数
app.use(formidableMiddleware({
	// 文件上传目录
	uploadDir: path.join(__dirname, 'public', 'uploads'),
	// 最大上传文件为2M
	maxFileSize: 2 * 1024 * 1024,
	// 保留文件扩展名
	keepExtensions: true
}));

app.use(express.static(path.join(__dirname,'public')));
app.use('/upload',uploads)
app.use('/class',classify)
app.use('/article',article)
app.use('/tag',tag)
app.use('/content',content)
app.use('/message',message)

const secretKey = 'myblog No1 ^-^'

app.use('/admin',expressJWT({secret:secretKey,algorithms: ['HS256']}),(err,req,res,next)=>{
	if(err.name==='UnauthorizedError'){
		return res.status(400).send({
			msg:'token无效'
		})
	}
	next()
})


app.use('/admin',admin)

app.post('/login',require('./router/login'))

app.listen(3000,()=>{
    console.log('服务器已启动，运行在localhost:3000')
})